package com.trip.service;

import com.trip.dao.tables.records.FriendShipRecord;
import com.trip.exception.ServiceException;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import static com.trip.dao.Tables.FRIEND_SHIP;
import static com.trip.dao.Tables.USER;

/**
 * Created by hc24 on 2017/10/9.
 */
@Service
@Transactional
public class FriendShipService {

    @Autowired
    private DSLContext dslContext;

    @Autowired
    private TripPlanService tripPlanService;

    public void addFriend(Integer userId,Integer friendId){
        if(userId.equals(friendId))
            throw new ServiceException("You can't add yourself");
        if(dslContext.selectCount().from(USER)
                .where(USER.ID.eq(friendId))
                .fetchOne().value1()==0)
            throw new ServiceException("The user you'll add does not exist");

        if(dslContext.selectCount().from(FRIEND_SHIP)
                .where(FRIEND_SHIP.USER_ID.eq(userId),FRIEND_SHIP.FRIEND_ID.eq(friendId))
                .fetchOne().value1()>0)
            throw new ServiceException("You have added him as a friend");
        FriendShipRecord record= dslContext.newRecord(FRIEND_SHIP);
        record.setUserId(userId);
        record.setFriendId(friendId);
        record.setAddTime(LocalDateTime.now());

        record.insert();
    }

    public void removeFriend(Integer userId,Integer friendId){
        dslContext.deleteFrom(FRIEND_SHIP)
                .where(FRIEND_SHIP.USER_ID.eq(userId),FRIEND_SHIP.FRIEND_ID.eq(friendId))
                .execute();

        tripPlanService.deletePartner(userId,friendId);
    }
}
